package com.yfqy.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yfqy.admin.conf.Idgenerator.SnowflakeIdGenerator;
import com.yfqy.admin.constant.MyConstants;
import com.yfqy.admin.domain.dto.auth.AuthMenu;
import com.yfqy.admin.domain.dto.auth.AuthRole;
import com.yfqy.admin.domain.dto.auth.AuthUser;
import com.yfqy.admin.domain.dto.auth.Authority;
import com.yfqy.admin.domain.entity.Customer;
import com.yfqy.admin.domain.entity.SysUser;
import com.yfqy.admin.domain.mapper.CustomerMapper;
import com.yfqy.admin.domain.mapper.SysMenuMapper;
import com.yfqy.admin.domain.mapper.SysRoleMapper;
import com.yfqy.admin.domain.mapper.SysUserMapper;
import com.yfqy.admin.service.SystemUserService;
import com.yfqy.admin.util.NicknameGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @Author: 梁二东
 * @Date: 2025/5/6 19:00
 * @Description:
 **/
@Service
public class SystemUserServiceImpl implements SystemUserService {

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private SysMenuMapper menuMapper;
    @Autowired
    private CustomerMapper customerMapper;
    @Autowired
    private SnowflakeIdGenerator snowflakeIdGenerator;

    @Override
    public AuthUser getUserFromDB(String username) {
        SysUser user = userMapper.selectOneByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在或密码错误");
        }
        if (user.getStatus() != MyConstants.BT1) {
            throw new UsernameNotFoundException("用户被锁定或已删除");
        }
        // 合并角色和权限（示例逻辑）
        List<Authority> authorities = new ArrayList<>();
        AuthUser authUser = BeanUtil.toBean(user, AuthUser.class);
        List<AuthRole> roles = roleMapper.selectRolesByUserId(user.getId());
        List<AuthMenu> menus = null;
        if (CollUtil.isEmpty(roles)) {
            //authUser.setAuthorities(authorities);
            return authUser;
        } else if (roles.stream().anyMatch(role -> role.getIsAdmin() == 1)) {
            menus = menuMapper.selectMenusByAdmin();
            //authUser.setAuthorities();
        } else {
            List<Long> roleIds = roles.stream().map(AuthRole::getId).toList();
            menus = menuMapper.selectMenusByRoleIds(roleIds);
        }
        // 1. 添加角色（格式：ROLE_XXX）
        roles.forEach(role -> {
            authorities.add(new Authority("ROLE_" + role.getCode()));
        });
        // 2. 添加角色关联的权限
        authorities.addAll(
                Optional.ofNullable(menus)
                        .orElseGet(Collections::emptyList)
                        .stream()
                        .filter(perm -> perm != null && StringUtils.isNotBlank(perm.getCode()))
                        .map(perm -> new Authority(perm.getCode()))
                        .toList()
        );
        authUser.setAuthorities(authorities);
        return authUser;
    }

    @Override
    public AuthUser getUserByPhone(String phoneNumber) {
        Customer customer = customerMapper.selectOneByPhone(phoneNumber);
        if (customer == null) {
            // 使用手机号+验证码登录，如果用户不存在直接添加
            customer = new Customer();
            customer.setId(snowflakeIdGenerator.nextId());
            customer.setPhone(phoneNumber);
            customer.setGender(MyConstants.BT0);
            customer.setNickname(NicknameGenerator.nextNickname());
            customer.setIsDeleted(MyConstants.BT0);
            customerMapper.insertSelective(customer);
        } else if (MyConstants.BT1 == customer.getIsDeleted()) {
            throw new UsernameNotFoundException("用户被锁定或已删除");
        }
        return BeanUtil.toBean(customer, AuthUser.class);
    }

    @Override
    public String getUserNameById(Long id) {
        SysUser sysUser = userMapper.selectByPrimaryKey(id);
        if (Objects.isNull(sysUser)) {
            return "-";
        }
        return String.format("%s(%s)", sysUser.getNickname(), sysUser.getUsername());
    }
}
